lunomobs.experiences = { }

if minetest.setting_getbool("lunomobs_spawn")~= false then
	minetest.setting_set("lunomobs_spawn", "true")
end

if minetest.setting_getbool("lunomobs_sounds")~= false then
	minetest.setting_set("lunomobs_sounds", "true")
end

if minetest.setting_getbool("lunomobs_only_peaceful")~=true then 
	minetest.setting_set("lunomobs_only_peaceful","false")
end


if minetest.setting_getbool("display_mob_spawn")~=true then 
	minetest.setting_set("display_mob_spawn","false")
end

if minetest.setting_getbool("display_mob_death")~=true and minetest.setting_getbool("display_mob_death")~=false then 
  minetest.setting_set("display_mob_death","true")
end

if minetest.setting_getbool("display_mob_delete")~= true then --Se exibe mensagem de apagar mob da memoria
	minetest.setting_set("display_mob_delete", "false")
end

if minetest.setting_getbool("lunomobs_quests")~=true then 
	minetest.setting_set("lunomobs_quests","false")
end

minetest.register_on_dieplayer(function(player)
	--minetest.chat_send_all(player:get_player_name().." died.")
	if player~=nil and player:is_player() then
		lunomods.givePercentXP(player, -50, nil) --Perde 50% de XP do nivel 
		
		--[[
		local playername = player:get_player_name()
		local Xp = lunomods.getCharValue(playername, "Experience") or 0
		if Xp==nil or Xp=="" or type(Xp)~="number" or (type(Xp)=="number" and Xp<0) then 
			Xp=0 
		else
			Xp=math.floor(Xp)
		end
		local lvl = lunomods.getNivelPorExperiencia(Xp)
		local NewXp=lunomods.getExperienciaPosMorte(Xp)
		lunomods.setCharValue(playername, "Experience", NewXp)
		local lvlNEW = lunomods.getNivelPorExperiencia(NewXp)
		if lvl~=lvlNEW then
			--minetest.chat_send_player(playername, "Voce retornou para o "..(lvlNEW).."!!!")	
			minetest.chat_send_all(playername.." regrediu para o nivel "..(lvlNEW).."!!!")
			--lunomobs.doMobSFX(player, self, "sfx_leveldown", true)
			minetest.sound_play("sfx_leveldown", {object=player, max_hear_distance = 1000})  
		else
			--minetest.chat_send_player(playername, "Voce perdeu "..(NewXp - Xp).." pontos de experiencia!!!")	
			minetest.chat_send_all(playername.." perdeu "..(NewXp - Xp).." pontos de experiencia!!!")
		end
		]]--
	end
end)

lunomobs.doContObject = function(player, objectname, quantia) --
	if minetest.setting_getbool("lunomobs_quests") then
		if player~=nil and player:is_player() then
			if objectname~=nil and objectname~="" then
				if quantia~=nil and quantia>=1 then
					local playername = player:get_player_name()
					--objectname = objectname:gsub(":","_-_")
					local qtdObjectsAntiga = lunomods.getCharValue(playername, objectname) or 0
					local qtdObjectsNova = qtdObjectsAntiga + quantia
					lunomods.setCharValue(playername, objectname, qtdObjectsNova)
					--[[
					print("lunomobs.doContObject.playername="..playername)
					print("lunomobs.doContObject.objectname="..objectname)
					print("lunomobs.doContObject.quantia="..quantia)
					print("lunomobs.doContObject.qtdObjectsAntiga="..qtdObjectsAntiga)
					print("lunomobs.doContObject.qtdObjectsNova="..qtdObjectsNova)
					]]--
				else
					print("############################### [ERRO] Valor 'lunomobs.doContObject("..player:is_player()..", "..objectname..").quantia' invalido!")
				end
			else
				print("############################### [ERRO] Valor 'lunomobs.doContObject("..player:is_player()..").objectname' invalido!")
			end
		else
			print("############################### [ERRO] Valor 'lunomobs.doContObject.player' invalido!")
		end
	end
end

lunomobs.getRealAngle = function(self, yaw)
	if self.drawtype=="left" then
		yaw = yaw-(math.pi/2)
	elseif self.drawtype=="right" then
		yaw = yaw+(math.pi/2)
	elseif self.drawtype=="back" then
		yaw = yaw+(math.pi)
	end
	return yaw
end

lunomobs.doMobSFX = function(player, mob, sfxName, ifStop)
	if minetest.setting_getbool("lunomobs_sounds")~= false then
		if player~=nil and type(player)=="string" then
			player = minetest.env:get_player_by_name(player) --Transforma type "string" em tipo "player"
		end
		
		if player==nil or player:is_player()==nil or not player:is_player()
			or minetest.get_modpath("lunoturns") == nil
			or type(lunoturns)=="nil" --So verifica o modo mudo se o player for declarado. Se nao for declarado a funcao deixa acontecer normalmente.
			or (
				minetest.setting_getbool("lunomods_bgmusic") 
				and lunoturns.players[player:get_player_name()]~=nil 
				and lunoturns.players[player:get_player_name()].mute~=nil 
				and lunoturns.players[player:get_player_name()].mute==false
			) 
		then
			if mob~=nil and mob.object~=nil and mob.object:getpos()~=nil and sfxName~=nil and type(sfxName)=="string" and sfxName~="" then
				if ifStop~=nil and ifStop==true and mob.sound_buffer~=nil then 
					minetest.sound_stop(mob.sound_buffer) 
				end
				local dist = 0
				if mob.view_range==nil or type(mob.view_range)~="number" or mob.view_range<=0 then 
					dist = 15
				else
					dist = mob.view_range
				end
				mob.sound_buffer = minetest.sound_play(sfxName, {pos=mob.object:getpos(), max_hear_distance = dist})
			end
		end
	end
end

lunomobs.onPetRightClick = function(self, clicker)
	if self.type=="animal" then
		local itemWielded = clicker:get_wielded_item()
		--print("itemWielded:get_name() = "..dump(itemWielded:get_name()))
		local seFoodWielded = false
		if itemWielded~=nil and self.foods~=nil and type(self.foods)=="table" and #self.foods >=1 then
			for _,food in pairs(self.foods) do
				--print("food('"..dump(food).."')==itemWielded('"..itemWielded:get_name().."')")
				if food~=nil and food~="" and food==itemWielded:get_name() then
					seFoodWielded = true
					break
				end
			end
		end
		if self.tamed == nil or not self.tamed then
			lunomobs.doMobSFX(clicker, self, self.sounds.random, true)
			if seFoodWielded == true then
				self.tamed = true
				self.owner = clicker:get_player_name()
				minetest.chat_send_player(clicker:get_player_name(), "Voce domesticou este animal!")
				if not minetest.setting_getbool("creative_mode") then
					itemWielded:take_item()
					clicker:set_wielded_item(itemWielded)
				end
				lunomobs.doMobSFX(clicker, self, "obj_chew", false)
			else
				minetest.chat_send_player(clicker:get_player_name(), "Este animal ainda nao foi domesticado!")
			end
		else -- "else" de if self.tamed == nil or not self.tamed then
			if self.owner==nil or self.owner=="" or self.owner==clicker:get_player_name() then
				if seFoodWielded == true then
					if self.naked then
						self.food = (self.food or 0) + 1
						--print("self.food = "..self.food)
						if self.food >= 8 then
							self.food = 0
							self.naked = false
							--self.object:set_properties({ textures={"mobs_cow.png"}, mesh="mobs_cow.b3d", })
							if self.prop_unnaked ~= nil and type(self.prop_unnaked)=="table" then
								self.object:set_properties(self.prop_unnaked)
							end
							lunomobs.doMobSFX(clicker, self, self.sounds.random, true)
						end
					elseif self.pregnant_time == nil or type(self.pregnant_time)~="number" or self.pregnant_time <= 0 then
						self.pregnant_time = self.pregnant_delay + os.time() --Intervalo regressivo em segundos para ter filhotes
						minetest.chat_send_player(clicker:get_player_name(), "Este animal vai ter filhotes!")
						lunomobs.doMobSFX(clicker, self, self.sounds.random, true)
					end
					if not minetest.setting_getbool("creative_mode") then
						itemWielded:take_item()
						clicker:set_wielded_item(itemWielded)
					end
					lunomobs.doMobSFX(clicker, self, "obj_chew", false)
				elseif self.naker_tool~=nil and type(self.naker_tool)=="string" and self.naker_tool == itemWielded:get_name() then
					if self.naked==nil or not self.naked then
						self.naked = true
						if minetest.registered_items[self.naked_item] then
							clicker:get_inventory():add_item("main", ItemStack(self.naked_item.." 1")) --So dará uma
						end
						if self.prop_naked ~= nil and type(self.prop_naked)=="table" then
							self.object:set_properties(self.prop_naked)
						end
						lunomobs.doMobSFX(clicker, self, self.sounds.random, true)
					end
				elseif self.catch_tool~=nil and type(self.catch_tool)=="string" and self.catch_tool == itemWielded:get_name() then
					if minetest.registered_items[self.name] then
		  				if not minetest.setting_getbool("creative_mode") then
							itemWielded:take_item()
							clicker:set_wielded_item(itemWielded)
						end
						clicker:get_inventory():add_item("main", self.name.." 1") --Esta linha so deve ser executada depois de retirar consulmir o item da mao, ou dara erro. (nao sei o motivo!!!)
		  				self.object:remove()
						return true
		  			else
		  				print("#################### erro de item lunomobs.api")
					end
				end
			else -- "else" de if self.owner==nil or self.owner=="" or self.owner==clicker:get_player_name() then
				minetest.chat_send_player(clicker:get_player_name(), "Este animal nao te pertence!")
			end -- fim de "else" de if self.owner==nil or self.owner=="" or self.owner==clicker:get_player_name() then
		end -- fim de "else" de if self.tamed == nil or not self.tamed then
	end -- fim de if self.type=="animal" then
end

--#########################################################################################################

function lunomobs:register_mob(name, def)
	minetest.register_entity(name, {
		--pos = def.pos, --Fui eu quem criou , e sou eu quem esta desativando.
		random_names = def.random_names,
		selected_name = def.selected_name,
		mob_name = def.mob_name,
		hp_max = def.hp_max,
		xp_give = def.xp_give or 0,
		physical = true,
		tamed = def.tamed,
		lifetimer = 600,
		owner= def.owner,
		collisionbox = def.collisionbox,
		visual = def.visual,
		visual_size = def.visual_size,
		mesh = def.mesh,
		drawtype = def.drawtype, --"right"/"left"/"back"/"front" --default:"front"
		textures = def.textures,
		--random_textures = def.random_textures,
		makes_footstep_sound = def.makes_footstep_sound,
		view_range = def.view_range,
		walk_velocity = def.walk_velocity,
		walk_type = def.walk_type,
		old_walk_velocity = def.walk_velocity,
		run_velocity = def.run_velocity,
		walk_percent = def.walk_percent, --Probabilidade dele ficar andando. Varia de 0 ~ 100% do tempo
		fixed_y = def.fixed_y, --Serve para o personagem nao ficar olhando em volta (so funciona quando esta parado).
		damage = def.damage,
		light_damage = def.light_damage,
		shadow_damage = def.shadow_damage,
		water_damage = def.water_damage,
		lava_damage = def.lava_damage,
		disable_fall_damage = def.disable_fall_damage,
		drops = def.drops,
		armor = def.armor,
		pregnant_time = def.pregnant_time, --Contador decrescivo de tempo de gravidez
		pregnant_delay = def.pregnant_delay or 300, --Segundos que o mob ficara gravido.
		pregnant_drops = def.pregnant_drops, --Item que será dropado se mob estiver gravido.
		follow = def.follow, --Tipos de comidas que atraem este animal
		foods  = def.foods, --Tipos de comidas que domesticam este animal
		prop_unnaked = def.prop_unnaked,  --Aparencia do mob quando [[[NAO]]] extraido um item expecial.
		prop_naked = def.prop_naked, --Aparencia do mob quando extraido um item expecial.
		naker_tool = def.naker_tool, --Que ferramenta especial extrai algum item deste mob
		naked_item = def.naked_item, --Que tipo de item ser extraido deste mob usando ferramenta especial.
		catch_tool = def.catch_tool, --Que tipo de item pode capturar este mob. ""==mãos | nil==NaoCaptura
		damage_thief = def.damage_thief or 5, --Dano em caso alguem tente interagir um pet domesticado que nao lhe pertece.
		--after_place_mob = def.after_place_mob,
		--on_receive_fields = def.on_receive_fields,
		on_rightclick = def.on_rightclick or function(self, clicker)
			return lunomobs.onPetRightClick(self, clicker)
		end,
		type = def.type,
		loja_atual = def.loja_atual,
		attack_type = def.attack_type,
		spawner = def.spawner,
		hyper_aggressive = def.hyper_aggressive,
		arrow = def.arrow,
		shoot_interval = def.shoot_interval,
		sounds = def.sounds,
		sound_buffer = def.sound_buffer,
		bmg_buffer = def.bmg_buffer,
		animation = def.animation,
		jump = def.jump==nil or def.jump, --Se true/nil o Mod pula para subir em coisas. Se falso empaca em qualquer 1 bloco altura.
		timer = 0,
		env_damage_timer = 0, -- only if state = "attack"
		attack = {player=nil, dist=nil},
		state = "stand",
		v_start = false,
		old_y = nil,
		
		trader_inventory = def.trader_inventory,
		
		doCallMob = function(self, user, SeChamar) --fazer mob olhar para o jogador true=prender false=soltar
			if SeChamar then
				if self.fixed_y==nil or self.fixed_y==false then
					self.old_walk_velocity = self.walk_velocity
					self.fixed_y = true
					self.walk_velocity = 0
					self.set_velocity(self, 0)
					--self.jump = false
					self.state = "stand"
					self:set_animation("stand")
				end
				self.object:setyaw(user:get_look_yaw() + (math.pi /2))
			else
				self.fixed_y = false
				self.walk_velocity = self.old_walk_velocity
				self.old_walk_velocity = nil
				--self.jump = true
			end
		end,
		
		set_velocity = function(self, v)
			if self~=nil and self.object:getvelocity()~=nil and self.object:getvelocity().y~=nil then
				local yaw = self.object:getyaw()
				local x=0
				local z=0
				
				if yaw~=nil and v~=nil and v~=0 then
					yaw = lunomobs.getRealAngle(self, yaw)
					x = math.sin(yaw) * -v
					z = math.cos(yaw) * v
				else
					x=0
					z=0
				end
				self.object:setvelocity({x=x, y=self.object:getvelocity().y, z=z})
			end
		end,
		
		get_velocity = function(self)
			local v = self.object:getvelocity()
			return (v.x^2 + v.z^2)^(0.5)
		end,
		
		set_animation = function(self, type)
			if self.animation==nil then self.animation={ } end
			if self.animation.current==nil then self.animation.current = "" end
			
			if (type==nil or type=="" or type=="stand") and self.animation.current~="stand" then
				if self.animation.stand_start and self.animation.stand_end and self.animation.speed_normal then
					self.object:set_animation(
						{x=self.animation.stand_start,y=self.animation.stand_end},
						self.animation.speed_normal, 0
					)
					self.animation.current = "stand"
				end
			elseif type=="walk" and self.animation.current~="walk"  then
				if self.animation.walk_start and self.animation.walk_end and self.animation.speed_normal then
					self.object:set_animation(
						{x=self.animation.walk_start,y=self.animation.walk_end},
						self.animation.speed_normal, 0
					)
					self.animation.current = "walk"
				end
			elseif type=="run" and self.animation.current~="run"  then
				if self.animation.run_start and self.animation.run_end and self.animation.speed_run then
					self.object:set_animation(
						{x=self.animation.run_start,y=self.animation.run_end},
						self.animation.speed_run, 0
					)
					self.animation.current = "run"
				end
			elseif type=="punch" and self.animation.current~="punch"  then
				if self.animation.punch_start and self.animation.punch_end and self.animation.speed_normal then
					self.object:set_animation(
						{x=self.animation.punch_start,y=self.animation.punch_end},
						self.animation.speed_normal, 0
					)
					self.animation.current = "punch"
				end
			end
		end,
		
		on_step = function(self, dtime)
			if self ==nil then return end
			if dtime==nil or type(dtime)~="number" then dtime = 0 end
			
			if self~=nil and (self.type=="monster" or self.type=="boss") and minetest.setting_getbool("lunomobs_only_peaceful") then
				self.object:remove()
				return true
			end
			
			
			self.lifetimer = self.lifetimer - dtime
			if self.tamed==nil or self.tamed==false then --Se for salvagem nao domesticado.
				if self.lifetimer <= 0 then 
					if minetest.setting_getbool("display_mob_delete")== true then
						if self.mob_name~=nil and self.mob_name~="" then --Nao sei se esta linha sera executada, por isso estou adicionando este "print".
							minetest.log('action',"[LUNOMOBS] Removendo '"..self.mob_name.."' nao domesticado...")
						else
							minetest.log('action',"[LUNOMOBS] Removendo '"..self.name.."' nao domesticado...")
						end
					end
					self.object:remove()
					return true
					--[[
					local player_count = 0
					for _,obj in ipairs(minetest.env:get_objects_inside_radius(self.object:getpos(), 20)) do
						if obj~=nil and obj:is_player() then
							player_count = player_count+1
						end
					end
					if player_count==0 and self.state~="attack" then
						self.object:remove()
						return true
					end
					]]--
				end
			elseif self.type=="animal" then --Se for um animal domesticado
				if self.pregnant_time~=nil and self.pregnant_time >= 1 then --Se estiver para ter filhotes
					if self.pregnant_time <= os.time() then
						self.pregnant_time = 0
						--print("#self.pregnant_drops="..#self.pregnant_drops)
						if self.pregnant_drops~=nil and type(self.pregnant_drops)=="table" and #self.pregnant_drops>=1  then
							for nd, drop in ipairs(self.pregnant_drops) do
								if drop~=nil and drop.name~=nil then
									--print("drop.name="..drop.name)
									if minetest.registered_items[drop.name] ~= nil then
										if drop.chance==nil or type(drop.chance)~="number" or drop.chance<=0 then drop.chance = 1 end
										local chancerandom = math.random(1, drop.chance)
										--print("chancerandom(1:"..drop.chance..")="..chancerandom)
										if nd==#self.pregnant_drops or chancerandom==1 then --Ele so calcula as chances se o item nao for o ultimo que sempre tem chance 100%
											--print("nd<NumeroDoDrop>="..nd)
											--minetest.item_drop(ItemStack(drop.name), dropper, pos)
											local obj = minetest.env:add_item(self.object:getpos(), drop.name)
											if obj ~= nil then
												obj:get_luaentity().collect = true
												local x = math.random(1, 5)
												if math.random(1,2) == 1 then x = -x end
												local z = math.random(1, 5)
												if math.random(1,2) == 1 then z = -z end
												obj:setvelocity({x=1/x, y=obj:getvelocity().y+1, z=1/z})
								
												--[[
												-- FIXME this doesnt work for deactiveted objects
												if minetest.setting_get("remove_items") and tonumber(minetest.setting_get("remove_items")) then
													minetest.after(tonumber(minetest.setting_get("remove_items")), 
														function(obj)
															obj:remove()
														end, 
													obj)
												end
												]]--
												lunomobs.doMobSFX(nil, self, "mobs_born", true)
												break
											end
										end
									else --"else" de if minetest.registered_items[drop.name] ~= nil then
										minetest.log('error',"[LUNOMOBS] O Mob '"..self.mob_name.."' nao conseguiu engravidar do item desconhecido '"..drop.name.."'!")
									end
								end
							end -- Fim de "for"
						else -- "else" do if self.pregnant_drops~=nil and type(self.pregnant_drops)=="table" and #self.pregnant_drops>=1  then
							minetest.env:add_entity(self.object:getpos(), self.name)
							lunomobs.doMobSFX(nil, self, "mobs_born", true)
						end
					end
				end				
			end
			
			if self.object:getvelocity().y > 0.1 then
				local yaw = self.object:getyaw()
				yaw = lunomobs.getRealAngle(self, yaw)
				
				local x = math.sin(yaw) * -2
				local z = math.cos(yaw) * 2
				self.object:setacceleration({x=x, y=-10, z=z})
			else
				self.object:setacceleration({x=0, y=-10, z=0})
			end
			
			
			if self.disable_fall_damage==true and self.object:getvelocity().y==0 then
				if self.old_y==nil or self.old_y=="" then
					self.old_y = self.object:getpos().y
				else
					local d = self.old_y - self.object:getpos().y
					if d > 5 then
						local damage = d-5
						local newPlayerHP = self.object:get_hp()-damage
						if newPlayerHP<0 then newPlayerHP=0 end
						self.object:set_hp(newPlayerHP)
						local posMob = self.object:getpos()
						posMob.y = posMob.y-1
						
						if self.object~=nil and self.object:get_hp()~=nil and self.object:get_hp() <= 0 then
							if self.sounds~=nil and self.sounds.die~=nil then
								for _,player in pairs(minetest.env:get_objects_inside_radius(posMob, 10)) do --Testa se colide com algum jogador.
									if player~=nil and player:is_player() then
										lunomobs.doMobSFX(player, self, self.sounds.die, true)
									end
								end
							end
							self.object:remove()
							return true
						end
					end
					self.old_y = self.object:getpos().y
				end
			end
			
			self.timer = self.timer+dtime
			if self.state~="attack" then
				if self.timer < 1 then
					return
				end
				self.timer = 0
			end
			
			if self.sounds~=nil and self.sounds.random~=nil and self.object~=nil and math.random(1, 100) <= 5 then 
				lunomobs.doMobSFX(nil, self, self.sounds.random, true)
			end
			
			local do_env_damage = function(self)
				local pos = self.object:getpos()
				local n = minetest.env:get_node(pos)
				
				if self.light_damage~=nil and self.light_damage~=0
					and pos~=nil --and pos.y>0
					and minetest.env:get_node_light(pos)
					and minetest.env:get_node_light(pos) > 4
					and minetest.env:get_timeofday() > 0.2
					and minetest.env:get_timeofday() < 0.8
				then
					local newHP = self.object:get_hp()-self.light_damage
					if newHP < 0 then newHP = 0 end
					self.object:set_hp(newHP)
					
					local posMob = self.object:getpos()
					posMob.y = posMob.y-1
					if self.object:get_hp() <= 0 then
						if self.sounds~=nil and self.sounds.die~=nil then
							lunomobs.doMobSFX(nil, self, self.sounds.die, true)
						end
						self.object:remove()
						return true
					end
				end
				
				if self.shadow_damage~=nil and self.shadow_damage~=0
					and pos~=nil --and pos.y>0
					and minetest.env:get_node_light(pos)
					and minetest.env:get_node_light(pos) < 8
					and minetest.env:get_timeofday()*24 < 5.5
					and minetest.env:get_timeofday()*24 > 18.4
				then
					local newHP = self.object:get_hp()-self.shadow_damage
					if newHP < 0 then newHP = 0 end
					self.object:set_hp(newHP)
					local posMob = self.object:getpos()
					posMob.y = posMob.y-1
					if self.object:get_hp() <= 0 then
						if self.sounds~=nil and self.sounds.die~=nil then
							lunomobs.doMobSFX(nil, self, self.sounds.die, true)
						end
						self.object:remove()
						return true
					end
				end
				
				if self.water_damage~=nil and self.water_damage>0 and
					minetest.get_item_group(n.name, "water")~=0
				then
					local newHP = self.object:get_hp()-self.water_damage
					if newHP < 0 then newHP = 0 end
					self.object:set_hp(newHP)
					local posMob = self.object:getpos()
					posMob.y = posMob.y-1
					if self.object:get_hp() <= 0 then
						if self.sounds~=nil and self.sounds.die~=nil then
							lunomobs.doMobSFX(nil, self, self.sounds.die, true)
						end
						self.object:remove()
						return true
					end
				end
				
				if self.lava_damage~=nil and self.lava_damage>= 0 and
					minetest.get_item_group(n.name, "lava")~=0
				then
					local newHP = self.object:get_hp()-self.lava_damage
					if newHP < 0 then newHP = 0 end
					self.object:set_hp(newHP)
					local posMob = self.object:getpos()
					posMob.y = posMob.y-1
					if self.object:get_hp() <= 0 then
						if self.sounds~=nil and self.sounds.die~=nil then
							lunomobs.doMobSFX(nil, self, self.sounds.die, true)
						end
						self.object:remove()
						return true
					end
				end
			end
			
			if self.fixed_y==nil or self.fixed_y==false then
				self.env_damage_timer = self.env_damage_timer + dtime
				if self.state=="attack" and self.env_damage_timer > 1 then
					self.env_damage_timer = 0
					do_env_damage(self)
				elseif self.state~="attack" then
					do_env_damage(self)
				end
			
				if 
					(self.type=="monster" or self.type=="boss") 
					and minetest.setting_getbool("enable_damage") 
				then --funcao de dano
					for _,player in pairs(minetest.get_connected_players()) do
						local s = self.object:getpos()
						local p = player:getpos()
						local dist = ((p.x-s.x)^2 + (p.y-s.y)^2 + (p.z-s.z)^2)^0.5
						if self.view_range and dist < self.view_range then
							lunomobs:doAttack(self, player)
						end
					end
				end
			
				if self.follow~=nil and self.follow~="" and (self.following==nil or self.following==false) then
					for _,player in pairs(minetest.get_connected_players()) do
						local s = self.object:getpos()
						local p = player:getpos()
						local dist = ((p.x-s.x)^2 + (p.y-s.y)^2 + (p.z-s.z)^2)^0.5
						if self.view_range and dist < self.view_range then
							self.following = player
						end
					end
				end
			
				if self.following~=nil and self.following:is_player() then
					if self.following:get_wielded_item():get_name()~=self.follow then
						self.following = nil
						self.v_start = false
					else
						local s = self.object:getpos()
						local p = self.following:getpos()
						local dist = ((p.x-s.x)^2 + (p.y-s.y)^2 + (p.z-s.z)^2)^0.5
						if dist > self.view_range then
							self.following = nil
							self.v_start = false
						else
							local vec = {x=p.x-s.x, y=p.y-s.y, z=p.z-s.z}
							local yaw = 0
							if self.drawtype ~= "left" then
								yaw = math.atan(vec.z/vec.x)+math.pi/2
							else
								yaw = math.atan(vec.z/vec.x)-math.pi/2
							end
							yaw = lunomobs.getRealAngle(self, yaw)
							

							if p.x > s.x then
								yaw = yaw+math.pi
							end
							self.object:setyaw(yaw)
							
							if self.walk_velocity~=nil and self.walk_velocity > 0 then
								if dist > 2 then
									if self.v_start==nil or self.v_start==false then
										self.v_start = true
										self.set_velocity(self, self.walk_velocity)
									else
										if self.walk_type==nil or self.walk_type=="" or self.walk_type=="normal" then
											if self.jump~=nil and self.get_velocity(self) <= 0.5 and self.object:getvelocity().y==0 then
												if self.sounds~=nil and self.sounds.jump~=nil then
													lunomobs.doMobSFX(nil, self, self.sounds.jump, true)
												end
												local v = self.object:getvelocity()
												v.y = 5
												self.object:setvelocity(v)
											end
										elseif self.walk_type=="jump" and self.object:getvelocity().y==0 then
											if self.sounds~=nil and self.sounds.jump~=nil then
												lunomobs.doMobSFX(nil, self, self.sounds.jump, true)
											end
											local v = self.object:getvelocity()
											v.y = 5
											self.object:setvelocity(v)
											self:set_animation("walk")
										end
										self.set_velocity(self, self.walk_velocity)
										self:set_animation("walk")
									end
								else
									self.v_start = false
									self.set_velocity(self, 0)
									self:set_animation("stand")
								end
							end
							return
						end
					end
				end
			end			
			
			
			
			if self.state==nil or self.state=="" or self.state=="stand" then
				if (self.fixed_y==nil or self.fixed_y==false) and math.random(1, 4)==1 then
					self.object:setyaw(self.object:getyaw()+((math.random(0,360)-180)/180*math.pi))
					
					self.set_velocity(self, 0)
					self.set_animation(self, "stand")
				
					if self.walk_velocity~=nil and self.walk_velocity > 0 then
					
						if self.walk_percent==nil then self.walk_percent = 50 end
						
						if math.random(1, 100) <= self.walk_percent then
							if self.walk_type~=nil and self.walk_type=="jump" and self.object:getvelocity().y==0 then
								if self.sounds~=nil and self.sounds.jump~=nil then
									lunomobs.doMobSFX(nil, self, self.sounds.jump, true)
								end
								local v = self.object:getvelocity()
								v.y = 5
								self.object:setvelocity(v)
							end
							self.set_velocity(self, self.walk_velocity)
							self.state = "walk"
							self.set_animation(self, "walk")
						end
						
					end
				end
			elseif self.state=="walk" then
				if math.random(1, 100) <= 30 then
					self.object:setyaw(self.object:getyaw()+((math.random(0,360)-180)/180*math.pi))
				end

				if self.walk_velocity==nil then self.walk_velocity = 0 end

				if self.walk_type==nil or self.walk_type=="" or self.walk_type=="normal" then
					if self.jump~=nil and self.get_velocity(self) <= 0.5 and self.object:getvelocity().y==0 then
						if self.sounds~=nil and self.sounds.jump~=nil then
							lunomobs.doMobSFX(nil, self, self.sounds.jump, true)
						end
						local v = self.object:getvelocity()
						v.y = 5
						self.object:setvelocity(v)
					end
					self:set_animation("walk")
				elseif self.walk_type=="jump" and self.object:getvelocity().y==0 then
					if self.sounds~=nil and self.sounds.jump~=nil then
						lunomobs.doMobSFX(nil, self, self.sounds.jump, true)
					end
					local v = self.object:getvelocity()
					v.y = 5
					self.object:setvelocity(v)
					self:set_animation("walk")
				end
				
				if self.walk_percent==nil then self.walk_percent = 50 end
			
				if math.random(1, 100) <= (100 - self.walk_percent) then
					self.set_velocity(self, 0)
					self.state = "stand"
					self:set_animation("stand")
				else
					self.set_velocity(self, self.walk_velocity)
				end
			elseif self.state=="attack" and self.attack_type=="spawner" then
				
				if not self.attack.player or not self.attack.player:is_player() then
					self.state = "stand"
					self:set_animation("stand")
					return
				end
				local s = self.object:getpos()
				local p = self.attack.player:getpos()
				local dist = ((p.x-s.x)^2 + (p.y-s.y)^2 + (p.z-s.z)^2)^0.5
				
				if lunogauges~=nil and lunogauges.huds~=nil and lunogauges.huds.gaugehp_update~=nil and self.attack.player~=nil and self.attack.player:is_player() then 
					lunogauges.huds.gaugehp_update(self.attack.player) 
				end

				if dist > self.view_range or self.attack.player:get_hp() <= 0 then
					self.state = "stand"
					self.v_start = false
					self.set_velocity(self, 0)
					self.attack = {player=nil, dist=nil}
					self:set_animation("stand")
					return
				else
					self.attack.dist = dist
				end
				
				local vec = {x=p.x-s.x, y=p.y-s.y, z=p.z-s.z}
				local yaw = math.atan(vec.z/vec.x)+math.pi/2

				yaw = lunomobs.getRealAngle(self, yaw)
				if p.x > s.x then
					yaw = yaw+math.pi
				end
				self.object:setyaw(yaw)
				self.set_velocity(self, 0)
				self:set_animation("punch")
				
				
				local countSpawners = 0
				for _,obj in pairs(minetest.env:get_objects_inside_radius(s, self.view_range)) do --Testa se ja ha algum Curse por perto
					if obj~=nil and not obj:is_player() then
						if obj:get_luaentity().name ~= nil and obj:get_luaentity().name == self.spawner.mob then
							countSpawners = countSpawners + 1
						end
					end
				end
				
				if countSpawners < self.spawner.amount then
					minetest.env:add_entity({
						x=s.x+math.random(-self.spawner.dist, self.spawner.dist),
						y=s.y,
						z=s.z+math.random(-self.spawner.dist, self.spawner.dist)
					}, self.spawner.mob)
					local atcPlayer = self.attack.player
					if atcPlayer~=nil and atcPlayer:is_player() and self.spawner.sound~=nil and  type(self.spawner.sound)=="string" and self.spawner.sound~="" then
						lunomobs.doMobSFX(atcPlayer, self, self.spawner.sound, true)
					end
				end
				
				--[[
				if self.timer > self.shoot_interval and math.random(1, 100) <= 60 then
					self.timer = 0
					
					self:set_animation("punch")
					
					if self.sounds~=nil and self.sounds.attack~=nil then
						lunomobs.doMobSFX(self.attack.player, self, self.sounds.attack, true)
					end
					
					local p = self.object:getpos()
					p.y = p.y + (self.collisionbox[2]+self.collisionbox[5])/2
					local obj = minetest.env:add_entity(p, self.arrow)
					local amount = (vec.x^2+vec.y^2+vec.z^2)^0.5
					local v = obj:get_luaentity().velocity
					vec.y = vec.y+1
					vec.x = vec.x*v/amount
					vec.y = vec.y*v/amount
					vec.z = vec.z*v/amount
					obj:setvelocity(vec)
				end
				]]--
				
			elseif self.state=="attack" and self.attack_type=="dogfight" then
			
				if not self.attack.player or not self.attack.player:is_player() then
					self.state = "stand"
					self:set_animation("stand")
					return
				end

				local s = self.object:getpos()
				local p = self.attack.player:getpos()
				local dist = ((p.x-s.x)^2 + (p.y-s.y)^2 + (p.z-s.z)^2)^0.5
				
				if lunogauges~=nil and lunogauges.huds~=nil and lunogauges.huds.gaugehp_update~=nil and self.attack.player~=nil and self.attack.player:is_player() then 
					lunogauges.huds.gaugehp_update(self.attack.player) 
				end
				
				if dist > self.view_range or self.attack.player:get_hp() <= 0 
					or (self.hyper_aggressive~=true and landrush~=nil and landrush.get_owner(self.attack.player:getpos())~=nil)
				then -- Se matar o player
					self.state = "walk"
					self.v_start = true
					--self.set_velocity(self, 0)
					self.attack = {player=nil, dist=nil}
					self:set_animation("walk")
					return
				else
					self.attack.dist = dist
				end
				
				local vec = {x=p.x-s.x, y=p.y-s.y, z=p.z-s.z}
				local yaw = math.atan(vec.z/vec.x)+math.pi/2
				yaw = lunomobs.getRealAngle(self, yaw)
				if p.x > s.x then
					yaw = yaw+math.pi
				end
				self.object:setyaw(yaw)
  				if self.attack.dist~=nil and self.attack.dist > 2 then
					--minetest.chat_send_all("self.v_start='"..string.format("%s",self.v_start and "true" or "false").."'")
					if not self.v_start then
						self.v_start = true
						self:set_animation("run")
					end
					if self.walk_type==nil or self.walk_type=="" or self.walk_type=="normal" then
						if self.jump~=nil and self.get_velocity(self) <= 0.5 and self.object:getvelocity().y==0 then
							if self.sounds~=nil and self.sounds.jump~=nil then
								lunomobs.doMobSFX(self.attack.player, self, self.sounds.attack, true)
							end
							local v = self.object:getvelocity()
							v.y = 5
							self.object:setvelocity(v)
						end
					elseif self.walk_type=="jump" and self.object:getvelocity().y==0 then
						if self.sounds~=nil and self.sounds.jump~=nil then
							lunomobs.doMobSFX(nil, self, self.sounds.jump, true)
						end
						local v = self.object:getvelocity()
						v.y = 5
						self.object:setvelocity(v)
					end
					self.set_velocity(self, self.run_velocity)
				else
					self.set_velocity(self, 0)
					self:set_animation("punch")
					self.v_start = false
					if self.timer > 1 then
						self.timer = 0
						if self.sounds~=nil and self.sounds.attack~=nil then
							lunomobs.doMobSFX(self.attack.player, self, self.sounds.attack, true)
						end
						self.attack.player:punch(self.object, 1.0,  {
							full_punch_interval=1.0,
							damage_groups = {fleshy=self.damage}
						}, vec)
					end
				end
			elseif self.state=="attack" and self.attack_type=="shoot" then
				if not self.attack.player or not self.attack.player:is_player() then
					self.state = "stand"
					self:set_animation("stand")
					return
				end
				local s = self.object:getpos()
				local p = self.attack.player:getpos()
				local dist = ((p.x-s.x)^2 + (p.y-s.y)^2 + (p.z-s.z)^2)^0.5
				
				if lunogauges~=nil and lunogauges.huds~=nil and lunogauges.huds.gaugehp_update~=nil and self.attack.player~=nil and self.attack.player:is_player() then 
					lunogauges.huds.gaugehp_update(self.attack.player) 
				end

				if dist > self.view_range or self.attack.player:get_hp() <= 0 then
					self.state = "stand"
					self.v_start = false
					self.set_velocity(self, 0)
					self.attack = {player=nil, dist=nil}
					self:set_animation("stand")
					return
				else
					self.attack.dist = dist
				end
				
				local vec = {x=p.x-s.x, y=p.y-s.y, z=p.z-s.z}
				local yaw = math.atan(vec.z/vec.x)+math.pi/2

				yaw = lunomobs.getRealAngle(self, yaw)
				if p.x > s.x then
					yaw = yaw+math.pi
				end
				self.object:setyaw(yaw)
				self.set_velocity(self, 0)
				
				if self.timer > self.shoot_interval and math.random(1, 100) <= 60 then
					self.timer = 0
					
					self:set_animation("punch")
					
					if self.sounds~=nil and self.sounds.attack~=nil then
						lunomobs.doMobSFX(self.attack.player, self, self.sounds.attack, true)
					end
					
					local p = self.object:getpos()
					p.y = p.y + (self.collisionbox[2]+self.collisionbox[5])/2
					local obj = minetest.env:add_entity(p, self.arrow)
					local amount = (vec.x^2+vec.y^2+vec.z^2)^0.5
					local v = obj:get_luaentity().velocity
					vec.y = vec.y+1
					vec.x = vec.x*v/amount
					vec.y = vec.y*v/amount
					vec.z = vec.z*v/amount
					obj:setvelocity(vec)
				end
			end
		end,
		
		on_activate = function(self, staticdata, dtime_s) --Abrir dados no mob para quando o player retornar para perto do mob.
			self.object:set_armor_groups({fleshy=self.armor})
			self.object:setacceleration({x=0, y=-10, z=0})
			self.state = "stand"
			self.object:setvelocity({x=0, y=self.object:getvelocity().y, z=0})
			self.object:setyaw(math.random(1, 360)/180*math.pi)
			if staticdata then
				local tmp = minetest.deserialize(staticdata)
				if tmp and tmp.lifetimer then self.lifetimer = tmp.lifetimer - dtime_s end
				--print("self.lifetimer = "..self.lifetimer)
				if tmp and tmp.tamed then self.tamed = tmp.tamed end
				if tmp and tmp.owner then  self.owner = tmp.owner  end
				if tmp and tmp.selected_name then  self.selected_name = tmp.selected_name  end
				if tmp and tmp.pregnant_time and tmp.pregnant_time>0 then  self.pregnant_time = tmp.pregnant_time  end
			end
			if def.on_activate==nil then
				if self.type=="monster" or self.type=="boss" or self.type=="animal" then
					self.lifetimer = 600 - dtime_s --Tempo de vida de 10 minutos para "monster" e "boss" e "animal sem dono"
					if minetest.setting_getbool("lunomobs_only_peaceful") then
						if minetest.setting_getbool("display_mob_delete")== true then
							if self.mob_name~=nil and self.mob_name~="" then --Nao sei se esta linha sera executada, por isso estou adicionando este "print".
								minetest.log('action',"[LUNOMOBS] Removendo '"..self.mob_name.."' por ser agressivo...")
							else
								minetest.log('action',"[LUNOMOBS] Removendo '"..self.name.."' por ser agressivo...")
							end
						end
						self.object:remove()
						return true
					elseif self.lifetimer <= 0 and (self.owner==nil or self.owner=="") then
						if minetest.setting_getbool("display_mob_delete")== true then
							if self.mob_name~=nil and self.mob_name~="" then --Nao sei se esta linha sera executada, por isso estou adicionando este "print".
								minetest.log('action',"[LUNOMOBS] Removendo '"..self.mob_name.."' por envelhecimento...") 
							else
								minetest.log('action',"[LUNOMOBS] Removendo '"..self.name.."' por envelhecimento...") 
							end
						end
						self.object:remove()
						return true
					end
				end
			else
				def.on_activate(self, staticdata, dtime_s)
			end
		end,
		
		get_staticdata = function(self)  --Salva dados no mob para quando o player estiver longe.
			local tmp = {
				lifetimer = self.lifetimer,
				tamed = self.tamed,
				owner = self.owner,
				selected_name = self.selected_name,
				pregnant_time = self.pregnant_time,
			}
			return minetest.serialize(tmp)
		end,
		
		on_punch = function(self, hitter)
			if self~=nil and hitter~=nil and hitter:is_player() then
				if self.owner==nil or self.owner=="" or self.owner==hitter:get_player_name() then
					local posMob = self.object:getpos()
					posMob.y = posMob.y-1
					if self.object:get_hp() <= 0 then
						lunomobs.doContObject(hitter, "kill("..self.name..")", 1)
					
						if self.sounds~=nil and self.sounds.die~=nil then
							lunomobs.doMobSFX(hitter, self, self.sounds.die, true)
						end
						local Xp = lunomods.getCharValue(hitter:get_player_name(), "Experience") or 0
						if Xp==nil or Xp=="" or type(Xp)~="number" or (type(Xp)=="number" and Xp<0) then 
							Xp=0 
						else
							Xp=math.floor(Xp)
						end
						local NewXp=Xp+self.xp_give
						lunomods.setCharValue(hitter:get_player_name(), "Experience", NewXp)
						
						if self.spawner ~= nil and self.spawner.kills_children_on_die~=nil and self.spawner.kills_children_on_die==true and self.spawner.mob ~= nil and type(self.spawner.mob)=="string" and self.spawner.mob~="" then
							for _,obj in pairs(minetest.env:get_objects_inside_radius(self.object:getpos(), self.view_range)) do --Testa se ja ha algum Curse por perto
								if obj~=nil and not obj:is_player() then
									if obj:get_luaentity().name ~= nil and obj:get_luaentity().name == self.spawner.mob then
										obj:remove()
									end
								end
							end
						end

						if minetest.setting_getbool("display_mob_death")==true then 
							if self.type~=nil and self.type=="boss" then
								if self.mob_name~=nil and self.mob_name~="" then
									minetest.log('action',hitter:get_player_name().." venceu o chefe "..self.mob_name.."!!!")
									minetest.chat_send_all(hitter:get_player_name().." venceu o chefe "..self.mob_name.."!!!")
								else
									minetest.log('action',hitter:get_player_name().." venceu o chefe "..self.name.."!!!")
									minetest.chat_send_all(hitter:get_player_name().." venceu o chefe "..self.name.."!!!")
								end
								minetest.sound_play("sfx_levelup")  
							else
								if lunomods.getNivelPorExperiencia(Xp) < lunomods.getNivelPorExperiencia(NewXp) then
									minetest.sound_play("sfx_levelup", {object=hitter, max_hear_distance = 1000})  
									--lunomobs.doMobSFX(hitter, self, "sfx_levelup", true)
									minetest.chat_send_all(hitter:get_player_name().." passou para o nivel "..lunomods.getNivelPorExperiencia(NewXp).."!!!")
									--TABELA DE NÍVEIS: https://docs.google.com/spreadsheet/ccc?key=0AqRrmO-Uhm1tdFVMLTVZQ0FSVUotTVI4Wi11dk1xclE&usp=sharing
								else
									if self.xp_give~=nil and self.xp_give >0 then
										if self.mob_name~=nil and self.mob_name~="" then
											minetest.chat_send_player(hitter:get_player_name(), "+"..self.xp_give.." pontos de experiencia por derrotar "..self.mob_name.."!")
										else
											minetest.chat_send_player(hitter:get_player_name(), "Voce ganhou +"..self.xp_give.." pontos de experiencia!!!")
										end
									else
										if self.mob_name~=nil and self.mob_name~="" then
											minetest.chat_send_player(hitter:get_player_name(), "Voce derrubou '"..self.mob_name.."'!!!")
										end
									end
								end
							end
						end
						if lunoskins~=nil and lunoskins.updatepainel~=nil then lunoskins.updatepainel("agora") end --So atualiza o painel se o mod estiver instalado

						if self.drops~=nil then
							for _,drop in ipairs(self.drops) do
								if drop~=nil and drop.name~=nil then
									if minetest.registered_items[drop.name] ~= nil then
										--[[
										local questvalue = false
										local questname = ""
										if drop.quest ~= nil and type(drop.quest)=="string" and drop.quest~="" then 
											questvalue = lunomods.getCharValue(hitter:get_player_name(), questname)
											if questvalue~=true then questvalue=false end
										end
										]]--

										
										if drop.quest ~= nil and type(drop.quest)=="string" and drop.quest~="" then
											local questname = drop.quest
											local questvalue = lunomods.getCharValue(hitter:get_player_name(), questname)
											if questvalue~=true and drop.give ~= nil and type(drop.give)=="number" and drop.give>=1 then
												minetest.log('action',hitter:get_player_name().." completou a missao '"..questname.."'...")
												minetest.chat_send_all(hitter:get_player_name().." completou a missao '"..questname.."'...")
												lunomods.setCharValue(hitter:get_player_name(), questname, true)
												
												minetest.log('action',hitter:get_player_name().." recebeu '"..drop.give.." x "..drop.name.."' por derrotar '"..self.name.."'...")
												hitter:get_inventory():add_item("main", ItemStack(drop.name.." "..drop.give))
												lunomobs.doContObject(hitter, "drop("..drop.name..")", drop.give)
											end
										elseif drop.chance~=nil and type(drop.chance)=="number" and drop.chance>=1 and math.random(1, drop.chance)==1 then
											local nivel = lunomods.getNivelPorExperiencia(NewXp)
											local quantia = math.random(drop.min, (drop.max + math.floor(nivel/3))) --a cada 3 niveis sobre um de probabilidade de drop. math.ceil(arredonda para cima de 0.5), math.floor(arredonda para menor de 0.5)
											minetest.log('action',hitter:get_player_name().." recebeu '"..quantia.." x "..drop.name.."' por derrotar '"..self.name.."'...")
											hitter:get_inventory():add_item("main", ItemStack(drop.name.." "..quantia))
											lunomobs.doContObject(hitter, "drop("..drop.name..")", quantia)
										end
										
										--[[
										local quantia = 0
										if drop.give ~= nil and type(drop.give)=="number" and drop.give>=1 then 
											quantia = drop.give 
										elseif drop.min ~= nil and type(drop.min)=="number" and drop.min>=0 and drop.max ~= nil and type(drop.max)=="number" and drop.max>=0 then 
											
										end
										if questvalue==false then
											if quantia>=1 or math.random(1, drop.chance)==1 then
												if questname~="" then
													print(hitter:get_player_name().." completou a missao '"..questname.."'...")
													minetest.chat_send_all(hitter:get_player_name().." completou a missao '"..questname.."'...")
													lunomods.setCharValue(hitter:get_player_name(), questname, true)
												end
												print(hitter:get_player_name().." recebeu '"..quantia.." x "..drop.name.."' por derrotar '"..self.name.."'...")
												hitter:get_inventory():add_item("main", ItemStack(drop.name.." "..quantia))
												lunomobs.doContObject(hitter, "drop("..drop.name..")", quantia)
											end
										end
										]]--

									else
										if self.mob_name ~=nil and drop.name~=nil then
											minetest.log('error',"[LUNOMOBS] O Mob '"..self.mob_name.."' nao conseguiu dropar item desconhecido '"..drop.name.."'!")
										else
											minetest.log('error',"[LUNOMOBS] O Mob '"..self.name.."' nao conseguiu dropar item desconhecido '"..drop.name.."'!")
										end
									end
								end --fim de if drop~=nil and drop.name~=nil then
							end -- fim de for _,drop in ipairs(self.drops) do
						end
					
						--[[
						if lunomobs.checkQuests~=nil then 
							lunomobs.checkQuests(hitter)
						end
						]]--

					else
						lunomobs:doAttack(self, hitter)
						if self.sounds~=nil and self.sounds.hit~=nil then
							lunomobs.doMobSFX(hitter, self, self.sounds.hit, true)
						end
					end
				elseif self.owner~=nil and type(self.owner)=="string" and self.owner~="" then
					self.object:set_hp(20)
					self.doCallMob(self, hitter, true)
					
					if self.damage_thief~=nil and type(self.damage_thief)=="number" and self.damage_thief>=1 then
						local newhp = hitter:get_hp() - self.damage_thief
						if newhp<0 then newhp = 0 end
						hitter:set_hp(newhp)
					end
					
					minetest.chat_send_player(hitter:get_player_name(), "Voce nao pode atacar um mob que nao te pertence.")
				
					local owneronline = minetest.env:get_player_by_name(self.owner) --Verifica se o dono esta online
					if owneronline~=nil and owneronline:is_player() and self.object~=nil and self.object:getpos()~=nil then
						if self.mob_name~=nil and type(self.mob_name)=="string" and self.mob_name~="" then
							minetest.chat_send_player(self.owner, hitter:get_player_name().." esta tentando destruir "..self.mob_name.." que pertece a voce.")
						else
							minetest.chat_send_player(self.owner, hitter:get_player_name().." esta tentando destruir um mob que pertece a voce.")
						end
						self.sound_buffer = minetest.sound_play("sfx_doorbell", {pos=self.object:getpos(), max_hear_distance = 1})
					end
					self.doCallMob(self, hitter, false)
				end
			end
		end,
		
	})
end

function lunomobs:doAttack(self, player)
	self.attack.dist=nil -- <== Serve para iniciar o recalculo de qual o jogador mais proximo do mob
	for _,player in pairs(minetest.get_connected_players()) do
		local s = self.object:getpos()
		local p = player:getpos()
		local dist = ((p.x-s.x)^2 + (p.y-s.y)^2 + (p.z-s.z)^2)^0.5
		
		if dist < self.view_range and (self.attack.dist==nil or dist<self.attack.dist) then
			if (landrush==nil or landrush.get_owner(player:getpos())==nil or self.hyper_aggressive==true) then
				self.state = "attack"
				self.attack.player = player
				self.attack.dist = dist
			end
		end
	end
end

lunomobs.spawning_mobs = {}
--lunomobs:register_spawn(name, {nodes}, max_light(0~20), min_light(0~20), chance(a cada x blocos de node), active_object_count(quantos spawn), max_height, spawn_func)
function lunomobs:register_spawn(name, nodes, max_light, min_light, chance, active_object_count, max_height, spawn_func)
	lunomobs.spawning_mobs[name] = true --Marca que o mob esta permitido ser gerado pelo mapa
	minetest.register_abm({
		nodenames = nodes,
		neighbors = {"air"},
		interval = 30,
		chance = chance,
		action = function(pos, node, active_object_count_real, active_object_count_wider)
			if minetest.setting_getbool("lunomobs_spawn")~= false then
				if active_object_count_wider > active_object_count then --Se ja tem mais objetos(active_object_count) do que o suportado(active_object_count_wider).
					return
				end
				if not lunomobs.spawning_mobs[name] then --Verifica se o mob esta proibido de ser gerado pelo mapa
					return
				end
				pos.y = pos.y+1
				if not minetest.env:get_node_light(pos) then --Se o local for 100% escuro, não gera mobs
					return
				end
				if minetest.env:get_node_light(pos) < min_light or minetest.env:get_node_light(pos) > max_light then --Se o local tiver luz abaixo ou acima do permitido, não gera mobs.
					return
				end
				if pos.y > max_height then -- se o local está acima da camada mais alta permitida.
					return
				end
				if minetest.env:get_node(pos).name~="air" then
					return
				end
				pos.y = pos.y+1
				if minetest.env:get_node(pos).name~="air" then
					return
				end
				if spawn_func~=nil and type(spawn_func)=="function" then --Executa esta funcao ao inves de desovar o mob.
					spawn_func(pos, node)
					return true --Executa uma funcao ao inves de instancia o mob.
				end 
				
				--[[
				local viewing_range_nodes_max = 80

				if minetest.setting_get("viewing_range_nodes_max")~=nil and minetest.setting_get("viewing_range_nodes_max")~="" then
					viewing_range_nodes_max = tonumber(minetest.setting_get("viewing_range_nodes_max"))
					viewing_range_nodes_max = math.floor(viewing_range_nodes_max * 0.33) --Enxerga mobs ate 33% da distancia maxima
					if viewing_range_nodes_max<=0 then viewing_range_nodes_max = 80 end
				end
				
				local objetos = minetest.env:get_objects_inside_radius(pos, viewing_range_nodes_max)
				local contPlayersProximos = 0
				for i , objeto in pairs(objetos) do
					if objeto:is_player() then
						contPlayersProximos = contPlayersProximos + 1
						break --Se tem jogadores perto, entao resume 'for' para aliviar a memoria e evitar lags
					end
					--print("objeto = "..i.."/"..#objetos)
					if i == #objetos then
						--print("contPlayersProximos = "..contPlayersProximos)
						if contPlayersProximos<=0 then --Se não houver jogadores proximos
							--print("###################### Nao ha player proximo do local de desova!!!!")
							for _,objeto in pairs(objetos) do
								if objeto~=nil and not objeto:is_player() 
									and objeto:get_luaentity()~=nil and objeto:get_luaentity().type ~= nil 
									and (
										objeto:get_luaentity().type == "monster" 
										or objeto:get_luaentity().type == "boss" 
									) 
								then
									objeto:remove()
									if minetest.setting_getbool("display_mob_delete")== true then
										if self.mob_name~=nil and self.mob_name~="" then --Nao sei se esta linha sera executada, por isso estou adicionando este "print".
											print("[LUNOMOBS] Excluindo '"..self.mob_name.."' no local de desova!!!") 
										else
											print("[LUNOMOBS] Excluindo '"..self.name.."' no local de desova!!!") 
										end
									end
								end
							end
							return --Nao gera monstro se nao houver players perto do local de desova de mob
						end
					end
				end-- fim do for
				]]--
				
					
				if minetest.setting_getbool("display_mob_spawn")~=false then
					minetest.chat_send_all("[lunomobs] Nascendo "..name.." em "..minetest.pos_to_string(pos)..".")
				end
			
				minetest.env:add_entity(pos, name)
			end
		end
	})
end

function lunomobs:register_arrow(name, def)
	minetest.register_entity(name, {
		physical = false,
		visual = def.visual,
		visual_size = def.visual_size,
		textures = def.textures,
		velocity = def.velocity,
		hit_player = def.hit_player,
		hit_node = def.hit_node,
		
		on_step = function(self, dtime)
			local pos = self.object:getpos()
			if minetest.env:get_node(self.object:getpos()).name~="air" then --Testa se colide com outro objeto que nao seja o ar.
				self.hit_node(self, pos)
				self.object:remove()
				return true
			end
			pos.y = pos.y-1
			for _,player in pairs(minetest.env:get_objects_inside_radius(pos, 1)) do --Testa se colide com algum jogador.
				if player:is_player() then
					self.hit_player(self, player)
					self.object:remove()
					return true
				end
			end
		end
	})
end
